package com.web.base.core.service;

import com.blue.core.dict.SeqType;
import com.blue.jdbc.JdbcDataSource;
import com.blue.jdbc.Page;
import com.web.base.core.dao.SequenceDao;
import com.web.base.core.exception.SequenceException;
import com.web.base.core.model.Sequence;
import com.web.core.util.Const;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service("coreSequenceService")
@Transactional
@JdbcDataSource(Const.DS_BASE)
public class SequenceService
{
	@Autowired
	private SequenceDao sequenceDao;
	
	public SequenceService()
	{
	}
	
	
	public Sequence save(Sequence seq)
	{
		if (sequenceDao.exist(seq, "code"))
			throw new SequenceException("序列已经存在：" + seq.getCode());
		
		if (seq.getId() == null)
		{
			sequenceDao.save(seq);
		}
		else
		{
			sequenceDao.update(seq);
		}
		Sequence s = sequenceDao.get(seq.getId());
		return s;
	}
	
	
	public void delete(Sequence seq)
	{
		sequenceDao.delete(seq);
	}
	
	
	public Sequence get(Integer id)
	{
		return sequenceDao.get(id);
	}
	
	
	public Page<Sequence> list(Sequence seq, Page<Sequence> page)
	{
		page = sequenceDao.list(seq, page);
		return page;
	}
	
	
	public Sequence getByCode(String code)
	{
		Sequence seq = sequenceDao.getByCode(code);
		if (seq == null)
			throw new SequenceException("不存在序列：" + code);
		
		if (seq.getType() == SeqType.NORMAL) // 普通
		{
			sequenceDao.updateVal(seq.getId(), seq.getVal() + 1, null);
			return seq;
		}
		else //日期
		{
			Date now = new Date();
			
			if (seq.getDate() == null) // 日期为空
			{
				seq.setDate(now);
				seq.setVal(1);
				
				sequenceDao.updateVal(seq.getId(), 2, now);
			}
			else
			{
				if (DateUtils.isSameDay(now, seq.getDate())) // 日期为今天
				{
					sequenceDao.updateVal(seq.getId(), seq.getVal() + 1, null);
				}
				else // 不是今天
				{
					seq.setDate(now);
					seq.setVal(1);
					
					sequenceDao.updateVal(seq.getId(), 2, now);
				}
			}
			
			return seq;
		}
	}
	
}
